/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"

#define LED_INTERVAL_TIME_US 300000
#define LED_TASK_STACK_SIZE 1024
#define LED_TASK_PRIO 25
#define RET_OK 0
#define RET_FAIL 1

static unsigned int lastTickCount = 0;
static unsigned int led_Level = 0;

//GPIO5中断回调函数
void GpioPressedIsrFunc(char *arg)
{
    (void)arg;

    //消除按键抖动
    unsigned int tickCount = osKernelGetTickCount();
    unsigned int count = tickCount - lastTickCount;
    lastTickCount = tickCount;

    if (count > 50)
    {
        led_Level ^= 1;
        IoTGpioSetOutputVal(IOT_GPIO_IO_GPIO_9, led_Level);
    }
}

static void *ClickKeyTask(const char *arg)
{
    (void)arg;
    unsigned int ret;

    printf("----- gpio isr demo -----\r\n");

    IoTGpioInit(IOT_GPIO_IO_GPIO_9);
    IoTIoSetFunc(IOT_GPIO_IO_GPIO_9, IOT_IO_FUNC_GPIO_9_GPIO);
    IoTGpioSetDir(IOT_GPIO_IO_GPIO_9, IOT_GPIO_DIR_OUT);
    IoTGpioSetOutputVal(IOT_GPIO_IO_GPIO_9, IOT_GPIO_VALUE0);

    //初始化GPIO5引脚
    IoTGpioInit(IOT_GPIO_IO_GPIO_5);
    IoTIoSetFunc(IOT_GPIO_IO_GPIO_5, IOT_IO_FUNC_GPIO_5_GPIO);
    IoTIoSetPull(IOT_GPIO_IO_GPIO_5, IOT_IO_PULL_UP);
    IoTGpioSetDir(IOT_GPIO_IO_GPIO_5, IOT_GPIO_DIR_IN);

    //设置GPIO5中断
    ret = IoTGpioRegisterIsrFunc(IOT_GPIO_IO_GPIO_5, IOT_INT_TYPE_EDGE,
                                 IOT_GPIO_EDGE_FALL_LEVEL_LOW, GpioPressedIsrFunc, NULL);
    if (ret != RET_OK)
    {
        printf("===== ERROR ======gpio -> hi_gpio_register_isr_function ret:%d\r\n", ret);
    }

    return NULL;
}

static void IotGpioClickKey(void)
{
    osThreadAttr_t attr;
    attr.name = "ClickKeyTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)ClickKeyTask, NULL, &attr) == NULL)
    {
        printf("[Talkweb Niobe] Falied to create ClickKeyTask!\n");
    }
    return;
}

APP_FEATURE_INIT(IotGpioClickKey);
